﻿@{
    ViewBag.Title = "Send Distress Call";
}

        <br />

<fieldset>
        <legend></legend>

        <p>
            Sender: <select id="senderDriverId" name="senderDriverId"><option value="abcde">jfluckiger</option>
<option value="fsiddiqui">fsiddiqui</option>
<option value="mkardonik">mkardonik</option>
<option value="bgene">bgene</option>
<option value="rjones">rjones</option>
<option value="sample2">sample</option>
<option value="test">fahdtest</option>

</select><br />
            <br />

            <button id="btnSendDistress">send distress</button>
            <br />
            <div id="responseToDistress"></div>
            <div id="distressCallResponse" style="visibility:hidden">
            	<p id="DistressFrom" style="visibility:hidden"></p>
            	<input type="button" id="btnAccept" onclick="accept()"
					value="Accept Distress Call" />
				<input type="button" onclick="reject()"
					value="Reject Distress Call" />
			</div>
            <div id="results"></div>
    </fieldset>


    </div>
<script src="http://html5demos.com/geo/js/h5utils.js"></script>  
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var n = 1;
    var waitingForDistressResponse = false;
    var answeringDistress = false;
    $(document).ready(function () {
        var query;
        $("#btnSendDistress").click(function () {
            //send distress
            waitingForDistressResponse = true;
            n = 1;
            var url = 'http://truckwatch.cloudapp.net/Services/GetNthClosestDriverLocationToMe?latitude=30&longitude=-97.6&nth=';
            $("#results").append('<p>Broadcasting a distress call, for n = ' + n + ' URL:' + url + n + '</p>');
            $.getJSON(url + n, callBack);
        });

        $("#btnAccept").click(function () {
            accept();
        });
    });

    function accept() {
        var from = document.getElementById("DistressFrom").innerHTML;
        document.getElementById("distressCallResponse").style.visibility = "hidden";
        $("#results").append('<p>Accepted to respond to distress from ' + from + '</p>');
        answeringDistress = true;
        sendMsg(from, "accepted distress");
    }

    function reject() {
        var from = document.getElementById("DistressFrom").innerHTML;
        document.getElementById("distressCallResponse").style.visibility = "hidden";
        $("#results").append('<p>Rejected to respond to distress from ' + from + '</p>');
        answeringDistress = false;
        sendMsg(from, "rejected distress");
    }

    function callBack(json) {
        //console.log("reached here");
        $("#results").append('<p>Received the closest driver: ' + json.UserId + '</p>');
        //send a message to the closest driver... 
        sendMsg(json.UserId, "distress call")
    }

    function sendMsg(recepient, msgTxt) {
        var w = document.getElementById("senderDriverId").selectedIndex;
        var msgType = "tt";
        var statusMsg = "test";
        var statusR = "test";
        var dataL = {
            senderUserId: document.getElementById("senderDriverId").options[w].text,
            recipientUserId: recepient,
            messageText: msgTxt,
            messageType: msgType,
            passhash: document.getElementById("senderDriverId").value,
            statusmessage: statusMsg,
            statusreason: statusR
        };
        var urlSendClosest = 'http://truckwatch.cloudapp.net/Services/SendMessage'; //Note: chanage this to absolute URL to test locally
        $("#results").append('<p>Calling ' + recepient + '. Sending msg: ' + msgTxt + ' for assistance, who is the closest.</p>');
        $.post(urlSendClosest, dataL, sendDistressCallback);
    }

    function sendDistressCallback(data, textStatus, jqXHR) {
        $("#results").append('<p>successfully sent message</p>');
    }


    var urlGetNextClosest = 'http://truckwatch.cloudapp.net/Services/GetNthClosestDriverLocationToMe?latitude=30&longitude=-97.6&nth=';
    function lookForNewMsgs() {
        var w = document.getElementById("senderDriverId").selectedIndex;
        var uid = document.getElementById("senderDriverId").options[w].text;
        var urlMsgs = 'http://truckwatch.cloudapp.net/Services/GetAllMessagesSinceAck?UserID=' + uid;

        $.getJSON(urlMsgs, callBackList);
    }
    function SetDistressFrom(id) {
        if (id == 1)
            document.getElementById("DistressFrom").innerHTML = 'jfluckiger';
        if (id == 2)
            document.getElementById("DistressFrom").innerHTML = 'fsiddiqui';
        if (id == 3)
            document.getElementById("DistressFrom").innerHTML = 'mkardonik';
        if (id == 4)
            document.getElementById("DistressFrom").innerHTML = 'bgene';
        if (id == 6)
            document.getElementById("DistressFrom").innerHTML = 'rjones';
        if (id == 7)
            document.getElementById("DistressFrom").innerHTML = 'sample';
        if (id == 8)
            document.getElementById("DistressFrom").innerHTML = 'fahdtest';
        if (id == 9)
            document.getElementById("DistressFrom").innerHTML = 'broadcast';
        if (id == 10)
            document.getElementById("DistressFrom").innerHTML = 'bhope';
    }
    function callBackList(json) {
        var maxAck = 0;
        $("#results").append('<p>Checking for new msgs...</p>');
        $.each(json, function (i, tweet) {
            if (tweet.Id > maxAck) {
                maxAck = tweet.Id;
            }
            if (tweet.MessageText.indexOf("distress call") > -1) {
                //if(!answeringDistress && !waitingForDistressResponse){
                //show Accept-Reject button and then send an "accepted distress or rejected" message
                document.getElementById("distressCallResponse").style.visibility = "visible";
                //document.getElementById("DistressFrom").innerHTML=tweet.SenderDriverId;
                SetDistressFrom(tweet.SenderDriverId);
                $("#results").append('<p>Received a distress call from ' + tweet.SenderName + '</p>');
                //}
            }
            if (tweet.MessageText.indexOf("accepted distress") > -1) {
                $("#results").append('<p><b>' + tweet.SenderName + ' is on his way!' + '</b></p>');
                $("#responseToDistress").append('<p><b>' + tweet.SenderName + ' is on his way!' + '</b></p>');
                waitingForDistressResponse = false;
            }
            if (tweet.MessageText.indexOf("rejected distress") > -1) {
                $("#results").append('<p>' + tweet.SenderName + ' has rejected the distress. Sending to the next closest!' + '</p>');
                $("#responseToDistress").append('<p><b>' + tweet.SenderName + ' has rejected the distress. Sending to the next closest!' + '</b></p>');
                n = n + 1;
                $.getJSON(urlGetNextClosest + n, callBack);
                waitingForDistressResponse = true;
            }
            $("#results").append('<p>SenderName: ' + tweet.SenderName + ' - Message: ' + tweet.MessageText + '</p>');
            $("#results").append('<p>Updating ack with Max: ' + maxAck + '</p>');
        });
        $("#results").append('<p>done...</p>');
        //Update Ack
        if (maxAck > 0) {
            $("#results").append('<p>Updating ack with Max: ' + maxAck + '</p>');
            UpdateAck(maxAck);
        }
    }

    function UpdateAck(max) {
        var w = document.getElementById("senderDriverId").selectedIndex;
        var dataL = {
            recipientUserId: document.getElementById("senderDriverId").options[w].text,
            ackNumber: max
        };
        var urlUpdateAck = 'http://truckwatch.cloudapp.net/Services/UpdateDriverAck'; //Note: chanage this to absolute URL to test locally
        $.post(urlUpdateAck, dataL, updatAckCallback);
    }
    function updatAckCallback(data, textStatus, jqXHR) {
        $("#results").append('<p>successfully updated ack...</p>');
    }
    setInterval(lookForNewMsgs, 5000);

</script>

